package main

import (
	"sync"
	"container/list"
)

var mutexSnakeType sync.Mutex

type SnakeType struct {
	sBody *list.List
	aMap  [][n] int
}

type PointXY struct {
	X int
	Y int
}

func CreateSnakeOnMap(screenMap [][n]int) *SnakeType {
	mutexSnakeType.Lock()
	defer mutexSnakeType.Unlock()

	snake := SnakeType{list.New(), screenMap}
	for y := 1; y <= 4; y++ {
		snake.sBody.PushFront(PointXY{n / 2, y})
	}
	for e := snake.sBody.Front(); e != nil; e = e.Next() {
		xyBODY := (e.Value).(PointXY)
		screenMap[xyBODY.X][xyBODY.Y] = mvSnakeBody
	}
	xyHEAD := (snake.sBody.Front().Value).(PointXY)
	screenMap[xyHEAD.X][xyHEAD.Y] = mvSnakeHeadValue
	return &snake
}

func (snake *SnakeType)Direction() *PointXY {
	mutexSnakeType.Lock()
	defer mutexSnakeType.Unlock()

	p0 := snake.sBody.Front().Value.(PointXY)
	p1 := snake.sBody.Front().Next().Value.(PointXY)
	return &PointXY{p0.X - p1.X, p0.Y - p1.Y}
}

func (snake *SnakeType)Move(direction *PointXY) {
	mutexSnakeType.Lock()
	defer mutexSnakeType.Unlock()

	pFrontXY := snake.sBody.Front().Value.(PointXY)
	pBackXY := snake.sBody.Back().Value.(PointXY)
	pNewXY := PointXY{pFrontXY.X + direction.X, pFrontXY.Y + direction.Y}
	snake.sBody.PushFront(pNewXY)
	if (snake.aMap[pNewXY.X][pNewXY.Y] == mvSpace) {
		snake.sBody.Remove(snake.sBody.Back())
		snake.aMap[pBackXY.X][pBackXY.Y] = mvSpace
	} else if (snake.aMap[pNewXY.X][pNewXY.Y] == mvFoodApple) {
	} else {
		GAME_OVER_BOOL_FLAG = true
		return
	}
	snake.aMap[pNewXY.X][pNewXY.Y] = mvSnakeHeadValue
	snake.aMap[pFrontXY.X][pFrontXY.Y] = mvSnakeBody
}